/*
 * Reference: Web Apps code provided by Prof Charlie Garrod
 * can be used for educational purposes
 * */
package messagepasser;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DocReadDAOSQL {
	private List<Connection> connectionPool = new ArrayList<Connection>();

	private String jdbcDriver;
	private String jdbcURL;
	private String tableName;

	public DocReadDAOSQL(String jdbcDriver, String jdbcURL, String tableName) {
		this.jdbcDriver = jdbcDriver;
		this.jdbcURL    = jdbcURL;
		this.tableName  = tableName;

		createTable();
	}

	private synchronized Connection getConnection() {
		if (connectionPool.size() > 0) {
			return connectionPool.remove(connectionPool.size()-1);
		}

		try {
			Class.forName(jdbcDriver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new AssertionError(e);
		}

		try {
			return DriverManager.getConnection(jdbcURL);
		} catch (SQLException e) {
			throw new AssertionError(e);
		}
	}

	private synchronized void releaseConnection(Connection con) {
		connectionPool.add(con);
	}

	private void createTable() {
		Connection con = getConnection();
		try {
			Statement stmt = con.createStatement();
			stmt.executeUpdate(
					"create table "+tableName+
					" (username varchar(20) NOT NULL," +
					" updates varchar(30)," +
					" id MEDIUMINT auto_increment, primary key(id)," +
			" foreign key(username) references aj1_profile(username))");
			stmt.close();
			releaseConnection(con);
		} catch (SQLException e) {
			try { con.close(); } catch (SQLException e2) { /* ignore */ }
			System.out.println("Exception creating table: "+e);
			System.out.println("...assume it already exists");
		}
	}


	/*	
	public void setupdate(String update, String user){
try {

			Connection con = getConnection();
        	con.setAutoCommit(false);

        	int num = 0;
        	Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select id from "+tableName+" order by id");
            while (rs.next()) {
            	num = (rs.getInt("id"));
            }
            rs.close();
            stmt.close();

            PreparedStatement pstmt = con.prepareStatement("insert into "+tableName+" values (?,?,?)");
 //           Date d1 = new Date();
            pstmt.setString(1, user);
            pstmt.setString(2, update);
            pstmt.setInt(3, num+1);


            pstmt.executeUpdate();
            pstmt.close();

            con.commit();
            con.setAutoCommit(true);

            releaseConnection(con);

        } catch (SQLException e) {
            throw new AssertionError(e);
        }
	}
	 */
	public void initialize(){
		try {

			Connection con = getConnection();
			con.setAutoCommit(false);
			int num=0;
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select count(username) as cnt from "+tableName);
			while (rs.next()) {
				num = (rs.getInt("cnt"));
			}
			rs.close();
			stmt.close();
			if(num == 0)
			{
				PreparedStatement pstmt = con.prepareStatement("insert into "+tableName+" values (?,?,?)");

			}
			con.commit();
			con.setAutoCommit(true);

			releaseConnection(con);

		} catch (SQLException e) {
			throw new AssertionError(e);
		}
	}



	//To get contents of a given doc
	public synchronized String getDocContents(int docid) {
		try {
			Connection con = getConnection();
			//docInfo = new ArrayList<DocInfo>();
			StringBuilder s = new StringBuilder();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select location from document where docid = "+docid);
			String loc = null;
			while (rs.next()) {
				loc = (rs.getString("location"));
			}
			if(loc==null){
				System.out.println("Location Not Available");
				return null;
			}
			try{
				BufferedReader input = new BufferedReader(new FileReader(loc));

				String l = null;
				while((l=input.readLine())!=null){
					s.append(l);
					s.append(System.getProperty("line.separator"));
				}
				rs.close();
				stmt.close();
				releaseConnection(con);

			}
			catch(IOException ex){
				ex.printStackTrace();
			}
			return s.toString();
		}catch (SQLException e) {
			throw new AssertionError(e);

		}
		finally{

		}
	}


	// Write into a text doc
	public synchronized void setDocContents(int docid, String contents) {
		try {
			Connection con = getConnection();
			//docInfo = new ArrayList<DocInfo>();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select location from document where docid = "+docid);
			String loc = null;

			while (rs.next()) {
				loc = (rs.getString("location"));
			}
			if(loc==null){
				System.out.println("Location Not Available");
				return;
			}
			Writer out = new BufferedWriter(new FileWriter(loc));
			try{
				out.write(contents);
			}finally{
				out.close();
			}
			rs.close();
			stmt.close();
			releaseConnection(con);
		}
		catch(Exception e){
			e.printStackTrace();
			}
		}
	}
